const fs = require('fs')
const co = require('co')
const {
	select,
	selectOne,
	insert,
	insertBatch,
	update,
	executeSQL,
} = require('../db-mysql')

const table = 'tb_project'
const fields = [
	'id',
	'version',
	'name',
	'create_date',
	'introduction',
	'modify_date',
	'user_id',
	'team_id',
	'create_user',
	'test_server_url'
]
const apiDetailTable = 'tb_api_detail'
const projectVersionTable = 'tb_project_version'
const projectVersionFields = [
	'id',
	'version',
	'description',
	'project_data',
	'user_id',
	'project_id',
	'edit_user',
	'modify_date'
]

module.exports = {

	addProject: async function(params) {
		let values = []
		let addFields = fields.filter((val, idx) => {
			if (val == 'id' || val == 'version')
				return false
			if (val == 'create_date' || val == 'modify_date')
				values.push("NOW()")
			else
				values.push(`'${params[val] || ''}'`)
			return true
		});

		let {
			insertId: projectId,
		} = await insert({
			table,
			fields: addFields,
			values,
		});
		let testServerUrl = /^https?:/.test(params.test_server_url) ? params.test_server_url : `http://${params.test_server_url}`;
		let projectData = {
			name: params.name,
			project_name: params.name,
			version: '0.0.1',
			create_user: params.create_user,
			testServerUrl,
			tree: {
				'module-00000000': {
					id: "module-00000000",
					name: "module-默认模块1",
					// 节点类型
					type: 'module',
					// 父节点
					parentNodeId: '',
					// 前一个节点
					prevNodeId: '',
					// 下一个节点
					nextNodeId: '',
					// 第一个子节点
					firstChildId: 'api-00000000',
				},
				'api-00000000': {
					id: "api-00000000",
					name: "默认接口1",
					// 节点类型
					type: 'api',
					// 父节点
					parentNodeId: 'module-00000000',
					// 前一个节点
					prevNodeId: '',
					// 下一个节点
					nextNodeId: '',
					// 第一个子节点
					firstChildId: '',
				}
			},
			treeData: [{
				id: "module-00000000",
				text: "module-默认模块1",
				state: 'open',
				children: [{
					id: "api-00000000",
					text: "默认接口1",
					checked: true,
				}],
			}],
			modules: {
				id: "module-00000000",
				text: "module-默认模块1",
			},
			apis: {
				'api-00000000': {
					id: "api-00000000",
					name: "默认接口1",
					intro: "",
					method: "GET",
					path: "",
					contentType: "application/x-www-form-urlencoded",
					requestParameterList: [],
					responseParameterList: []
				},
			},
		};
		projectData = JSON.stringify(projectData);
		projectData = projectData.replace(/^["'`]|["'`]$/g, '');
		// tb_api_detail 项目api详情表
		await insert({
			table: apiDetailTable,
			fields: ['project_id', 'project_data'],
			values: [projectId, projectData]
		});
		// tb_project_version 项目版本管理表
		await insert({
			table: projectVersionTable,
			fields: ['description', 'project_data', 'user_id', 'project_id', 'edit_user', 'modify_date'],
			values: ["系统默认，初始化项目", projectData, params['user_id'], projectId, params.create_user, 'NOW()']
		});
		return true
	},

	listProject(userId, userRole) {
		let f = fields.map((val, idx) => {
			return `tp.${val}`
		})
		let SQL = `SELECT DISTINCT ${f.join(',')}, tt.name as team, tu.realname as user FROM tb_project tp`
		SQL += ' LEFT JOIN tb_user tu ON tu.id = tp.user_id'
		SQL += ' LEFT JOIN tb_team tt ON tt.id = tp.team_id'
		SQL += ' LEFT JOIN tb_team_and_user ttu ON ttu.team_id = tp.team_id'
		if (userRole != 0 && userRole != 1)
			SQL += ` WHERE ttu.user_id = ${userId}`
		SQL += ' ORDER BY tp.id DESC;'

		return executeSQL(SQL)
	},

	/**
	 * 更新项目信息
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	updateProject(params) {
		let updates = []
		if (params.introduction) {
			updates.push(`introduction = '${params.introduction}'`)
		}
		if (params.name) {
			updates.push(`name = '${params.name}'`)
		}
		if (params.test_server_url) {
			updates.push(`test_server_url = '${params.test_server_url}'`)
		}
		return update({
			table,
			updates,
			where: [`id = '${params.project_id}'`],
		})
	},

	getProjectById(projectId) {
		return co(function*() {
			let result = yield select({
				table,
				fields,
				where: [
					`id = ${projectId}`
				]
			})
			return result[0]
		})
	},

	lockProject(projectId, lockedUser) {
		return co(function*() {
			let result = yield selectOne({
				table,
				fields: [
					'is_locked',
					'locked_user'
				],
				where: [
					`id = ${projectId}`
				]
			})
			if (result.is_locked)
				return result
			return update({
				table,
				updates: [
					'is_locked = 1',
					`locked_user = '${lockedUser}'`,
					'modify_date = NOW()'
				],
				where: [`id = '${projectId}'`],
			})
		})
	},

	unlockProject(projectId) {
		return update({
			table,
			updates: [
				'is_locked = 0',
				'locked_user = ""',
				'modify_date = NOW()'
			],
			where: [`id = '${projectId}'`],
		});
		// return co(function*() {
		// 	yield update({
		// 		table,
		// 		updates: [
		// 			'is_locked = 0',
		// 			'locked_user = ""',
		// 			'modify_date = NOW()'
		// 		],
		// 		where: [`id = '${projectId}'`],
		// 	})
		// 	return getProjectData(projectId)
		// })
	},

	/**
	 * 接口版本信息列表
	 * @param  {[type]} projectId [description]
	 * @return {[type]}           [description]
	 */
	projectVersionList(params) {
		let {
			project_id,
			page = 1,
			rows = 10,
		} = params
		page = parseInt(page) || 1
		rows = parseInt(rows) || 10
		let skip = (page - 1) * rows
		return co(function*() {
			let SQL = `SELECT COUNT(id) AS total FROM ${projectVersionTable} WHERE project_id = '${project_id}';`
			let total = yield executeSQL(SQL)
			total = Array.isArray(total) ? total[0] : total
			total = total.total
			let result = yield select({
				table: projectVersionTable,
				fields: projectVersionFields,
				where: [`project_id = '${project_id}'`],
				condition: `ORDER BY id DESC LIMIT ${skip}, ${rows}`
			})
			return {
				rows: result,
				total,
			}
		})
	},

}